import userTpl from '../views/user.html'
import handlebar from 'handlebars'
import { get, post } from '../model/http'

class UserController {

  constructor() {
    this.user = {
      //是否登录
      islogin: false,
      //用户名
      username: 'hanye',
      //是否显示登录
      showlogin: false
    }
    this._initEvent();
    this._islogin();
    this.render();
  }

  render() {
    let html = handlebar.compile(userTpl)(this.user)
    $("#user-container").html(html);
  }

  _initEvent() {
    let $userContainer = $("#user-container");
    //登录点击事件
    $userContainer.on('click', '#login', () => this._setInfo('登录', true))
    //注册点击事件
    $userContainer.on('click', '#signin', () => this._setInfo('注册', false))
    //登录、注册
    $userContainer.on('click', '#btn_submit', () => this._submit())
    //退出
    $userContainer.on('click', '#btn_logout', () => this._logout())

  }


  //设置标题，是否为登录状态
  _setInfo(title, showlogin) {
    $(".box-title").html(title)
    this.user.showlogin = showlogin;
  }


  //登录 & 注册
  async _submit() {
    console.log('submit...')
    let url = '/api/user/signin'
    if (this.user.showlogin) {
      url = "/api/user/login"
    }
    let params = $("#user-form").serialize();
    let rs = await post(url, params)
    if (rs.code === 1) {
      let token = rs.xhr.getResponseHeader("x-access-token")
      if (token) {
        localStorage.setItem('token', token);
      }
      this.user.username = rs.username;
      this.user.islogin = true;
      this.render();
    }
    alert(rs.message);
  }


  //退出
  async _logout() {
    let url = '/api/user/logout';
    let res = await get(url)
    console.log(res)
    if (res.code === 1) {
      this.user.username = '';
      this.user.islogin = false;
      this.render();
    } else {
      alert(res.message)
    }
  }

  //判断用户是否为登录状态
  async _islogin() {
    let result = await get("/api/user/islogin");
    if (result.code === 1) {
      this.user.username = result.username;
      this.user.islogin = true;
      this.render();
    } else {
      console.log(result)
    }
  }

}


export default new UserController();